package com.yuchen.utils.config;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Jack Q
 */
public class Config {

    private final static Logger LOG = Logger.getLogger(Config.class);

//    private static final String DEFAULT_CONFIG = "/systemConfig.properties";

    private Map<Object, Object> map = new HashMap<Object, Object>();

    private volatile static Config conf;

    private static Config me() {
        if (null == conf) {
            synchronized (Config.class) {
                if (null == conf)
                    conf = new Config();
            }
        }
        return conf;
    }

    private Config() {
        // 加载框架自己的一些配置
        //loadConf(DEFAULT_CONFIG);
    }


    public  String get(String key) {
        return (String) map.get(key);
    }

    public static Config load(String... resources) {
        me().loadConf(resources);
        return conf;
    }

    private void loadConf(String... resources) {
        InputStreamReader inputStream = null;
        Properties properties = new Properties();
        try {
            //ConfigUtils.class.getClassLoader().getResourceAsStream(resource) 加载自身jar 中classpath里面的文件路径
            //ConfigUtils.class.getResourceAsStream(resource) 加载应用里的classpath里的文件路径
            for(String resource : resources){
                InputStream in = Config.class.getResourceAsStream(resource);
                if(null == in){
                    continue;
                }
                inputStream = new InputStreamReader(in, "UTF-8");
                properties.load(inputStream);
                for(Map.Entry<Object, Object> entry : properties.entrySet() ){
                    map.put(entry.getKey(),entry.getValue());
                }
            }
        } catch (IOException e) {
            LOG.error("加载properties错误：" + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
